# @author: uuz
# encoding = utf-8
from datetime import datetime

from flask import Blueprint, jsonify
from flask_restful import Resource, reqparse, Api, abort
from sqlalchemy import event

from ext import db
from models import Hotel, Room, User, Order

order_bp = Blueprint("order", __name__, url_prefix='/api/order')
api = Api(order_bp)


# 创建订单（预订）
class NewOrderView(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('hotel_id', type=int, required=True)
        self.parser.add_argument('user_id', type=int, required=True)
        self.parser.add_argument('room_id', type=int, required=True)
        self.parser.add_argument('create_date', type=str, required=False, default=datetime.now)
        self.parser.add_argument('checkin_date', type=str, required=False, default=datetime.now)
        self.parser.add_argument('checkout_date', type=str, required=False, default=datetime.now)

    def post(self):
        args = self.parser.parse_args()
        hotel_id = args.get('hotel_id')
        user_id = args.get('user_id')
        room_id = args.get('room_id')
        create_date = args.get('create_date')
        checkin_date = args.get('checkin_date')
        checkout_date = args.get('checkout_date')
        if (Hotel.query.filter(Hotel.id == hotel_id).first() and
                Room.query.filter(Room.id == room_id).first() and
                User.query.filter(User.id == user_id).first()):
            order = Order(hotel_id=hotel_id,
                          user_id=user_id,
                          room_id=room_id,
                          create_date=create_date,
                          check_in=checkin_date,
                          check_out=checkout_date,
                          status=1)
            db.session.add(order)
            db.session.commit()
            return jsonify({"result": "添加订单成功"})
        else:
            abort(400, message='输入订单信息有误')


api.add_resource(NewOrderView, '/Order-Create/')


# 入住
class CheckinView(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('order_id', type=int, required=True)

    def post(self):
        args = self.parser.parse_args()
        order_id = args.get('order_id')
        order = Order.query.filter(Order.id == order_id).first()
        if order:
            if order.status == 1:
                order.status = 2
                db.session.commit()
                return jsonify({"result": "办理入住成功"})
            else:
                abort(400, message="订单状态错误")
        else:
            abort(400, message="订单不存在")


api.add_resource(CheckinView, '/checkin/')


# 离店
class CheckoutView(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('order_id', type=int, required=True)

    def post(self):
        args = self.parser.parse_args()
        order_id = args.get('order_id')
        order = Order.query.filter(Order.id == order_id).first()
        if order:
            if order.status != 3:
                order.check_out = datetime.now()
                order.status = 3
                room = Room.query.filter(Room.id == order.room_id).first()
                room.remains += 1
                db.session.commit()
                return jsonify({"result": "退店成功"})
            else:
                abort(400, message="订单状态错误")
        else:
            abort(400, message="订单不存在")


api.add_resource(CheckoutView, '/checkout/')


# 查看订单总价
class TotalPriceView(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()

    def get(self):
        args = self.parser.parse_args()
        orders = Order.query.all()
        lst = []
        for order in orders:
            lst.append({
                "id": order.id,
                "total": (order.check_out - order.check_in).days * order.room.price
            })
        return jsonify(lst)


api.add_resource(TotalPriceView, '/TotalList/')


class QueryOrderById(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('order_id', type=int, required=True)

    def get(self):
        order_id = self.parser.parse_args().get('order_id')
        order = Order.query.filter(Order.id == order_id).first()
        if order:
            return {
                "id": order.id,
                "hotel_id": order.hotel_id,
                "hotel_name": order.hotel.name,
                "room_id": order.room_id,
                "user_id": order.user_id,
                "create_date": str(order.create_date),
                "checkin": str(order.check_in),
                "checkout": str(order.check_out),
                "status": order.status,
                "total": (order.check_out - order.check_in).days * order.room.price,
                "days": (order.check_out - order.check_in).days
            }
        else:
            abort(400, message="订单编号不存在")


api.add_resource(QueryOrderById, '/QueryById/')


class QueryOrderByUserId(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('user_id', type=int, required=True)

    def get(self):
        user_id = self.parser.parse_args().get('user_id')
        orders = Order.query.filter(Order.user_id == user_id).all()
        if orders:
            lst = []
            for order in orders:
                lst.append({
                    "id": order.id,
                    "hotel_id": order.hotel_id,
                    "hotel_name": order.hotel.name,
                    "room_id": order.room_id,
                    "user_id": order.user_id,
                    "create_date": str(order.create_date),
                    "checkin": str(order.check_in),
                    "checkout": str(order.check_out),
                    "status": order.status,
                    "total": (order.check_out - order.check_in).days * order.room.price,
                    "days": (order.check_out - order.check_in).days
                })
            return lst
        else:
            abort(400, message="该用户无订单")


api.add_resource(QueryOrderByUserId, '/QueryByUserId/')
